//
//  AliveForeverThread.m
//  Charles
//
//  Created by Charles on 2020/3/13.
//  Copyright © 2020 charles. All rights reserved.
//

#import "AliveForeverThread.h"

static NSThread *thred = nil;
static BOOL runAlways = YES;

@implementation AliveForeverThread

+ (NSThread *)threadForDispatch {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        thred = [[NSThread alloc]initWithTarget:self selector:@selector(runRequest) object:nil];
        [thred setName:@"charles_alive_thread"];
        [thred start];
    });
    return thred;
}

+ (void)runRequest {
    // 创建一个Source
    CFRunLoopSourceContext context = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
    CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
    
    // 创建RunLoop
    CFRunLoopAddSource(CFRunLoopGetCurrent(), source,kCFRunLoopDefaultMode);
    
    // 开始运行
    while (runAlways) {
        @autoreleasepool {
            // 使当前RunLoop运行在DefaultMode下。
            CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, true);
        }
    }
    
    // 某一时机，runAlways = NO 时，可以保证跳出RunLoop,线程退出。
    CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
    CFRelease(source);
    NSLog(@"线程退出了！！");
}

+ (void)stopThread {
    runAlways = NO;
}

@end
